package com.cy.dda.comm.interceptor;

import java.lang.reflect.Field;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.cy.dda.comm.annotation.OssUrl;
import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.utils.CommonUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * oss拦截器，获取访问链接
 *
 * @author: tanyilin
 * @create: 2018年10月29日 上午10:52:19
 */
@Slf4j
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class OssUrlInterceptor implements Interceptor{

	@Autowired
	private OSSClient ossClient;

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object result = invocation.proceed();
		if(result instanceof List) {
			List list = (List) result;
			if(list.stream().noneMatch(obj -> obj.getClass().isAnnotationPresent(OssUrl.class))) {
				// 没有标有 @OssUrl 注解的，直接返回结果集
				return result;
			}
			
			// 2 个小时 的访问时间
			Date expiration = CommonUtils.addTime(new Date(), 2, Calendar.HOUR_OF_DAY);
			String style = "image/resize,p_50";
			
			list.stream().filter(obj -> obj.getClass().isAnnotationPresent(OssUrl.class)).forEach(obj -> {
				// 获取实体类的所有属性，返回Field数组
				Field[] fields = obj.getClass().getDeclaredFields();
				Stream.of(fields).filter(f -> f.isAnnotationPresent(OssUrl.class))
						.filter(f -> String.class.equals(f.getType()))
						.forEach(f -> {
							// 设置些属性是可以访问的
							f.setAccessible(true);
							try {
								Object value = f.get(obj);
								String key = String.valueOf(value);
								URL url = ossClient.generatePresignedUrl(Constants.BUCKETNAME, key, expiration);
//								URL url = null;
//								String bucketName = Constants.BUCKETNAME;
//								String suffix = key.substring(key.lastIndexOf("."));
//								if(Constants.IMAGE_SUFFIX.contains(suffix)) {
//									// 如果是可裁剪、缩放的图片
//									// 设置图片缩放处理样式。
//									GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
//									req.setExpiration(expiration);
//									req.setProcess(style);
//									url = ossClient.generatePresignedUrl(req);
//
//								}else {
//									url = ossClient.generatePresignedUrl(bucketName, key, expiration);
//								}
								f.set(obj, url.toString());
								
							} catch (IllegalArgumentException e) {
								log.error("OssUrlInterceptor intercept error:", e);
							} catch (IllegalAccessException e) {
								log.error("OssUrlInterceptor intercept error:", e);
							}
						});
			});
		}
		
		return result;
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		
	}
	
	
	
}
